<template>
	<div>
		<div class="search_box">
			<el-form :inline="true" class="demo-form-inline">
				<el-form-item>
					<el-button type="primary" @click="onAdd"
						>添加角色</el-button
					>
				</el-form-item>
			</el-form>
		</div>
		<el-table :data="list" border style="width: 100%">
			<el-table-column prop="roleId" label="角色ID" width="180" />
			<el-table-column prop="roleName" label="角色名" width="180" />
			<el-table-column label="操作" prop="authority">
				<template #default="scope">
					<el-button
						size="small"
						type="primary"
						@click="onEdit(scope.row)"
					>
						修改权限
					</el-button>
				</template>
			</el-table-column>
		</el-table>
	</div>
</template>

<script lang="ts">
import {
	defineComponent,
	toRefs,
	ref,
	computed,
	reactive,
	watch,
	onMounted,
} from 'vue'
import { getRolesList } from '../request/api'
import { InitData, ListInt } from '../type/roles'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

export default defineComponent({
	name: 'RoleView',
	setup() {
		const getRoles = async () => {
			let res = await getRolesList()
		}
		onMounted(() => {
			// getRoles
		})

		const roleData = reactive([
			{
				roleName: '管理员',
				roleId: 1,
				authority: [1, 2, 3, 4, 5, 6, 7, 9], // 权限
			},
			{
				roleName: '普通用户',
				roleId: 2,
				authority: [1, 2, 3, 4], // 权限
			},
		])

		const data = reactive(new InitData())
		data.list = roleData

		const onAdd = () => {
			ElMessageBox.prompt('请输入角色名称', '添加', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
			})
				.then(({ value }) => {
					// value 表示在输入框中填写的值
					if (value) {
						// 输入框中有值，就添加到角色列表中
						data.list.push({
							roleId: data.list.length + 1,
							roleName: value,
							authority: [],
						})
					}
					ElMessage({
						type: 'success',
						message: '添加成功',
					})
				})
				.catch(() => {
					ElMessage({
						type: 'info',
						message: '取消操作',
					})
				})
		}

		const router = useRouter()

		// 跳转至权限列表页面
		const onEdit = (row: ListInt) => {
			router.push({
				path: 'authority',
				query: {
					roleId: row.roleId,
					authority: row.authority.join(','),
				},
			})
		}

		return { ...toRefs(data), onAdd, onEdit }
	},
})
</script>

<style scoped></style>
